package JUC.PC;

import java.util.HashSet;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author mubei
 * @date 2021/11/21
 * @description 线程之间的通信问题  生产者消费者问题  通知等待唤醒
 * 线程交替进行   A  B  操作同一个变量   num = 0
 * A+1
 * B-1
 */
public class A {

    public static void main(String[] args) {

        Data data = new Data();

        new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
    }
}


class Data {
    private int number = 0;


    //+1
    public synchronized void increment() throws InterruptedException {
        while(number != 0){
            this.wait();
        }
      /* 虚假唤醒
        if (number != 0) {
            //等待
            this.wait();
        }*/
        System.out.println(Thread.currentThread().getName() + number);
        number++;
        //通知
        this.notifyAll();
    }

    //-1
    public synchronized void decrement() throws InterruptedException {
       while (number == 0) {
            //等待
            this.wait();
        }
        System.out.println(Thread.currentThread().getName() + number);
        number--;
        //通知
        this.notifyAll();
    }
}